import axios from 'axios'
import { baseUrl, defaultError } from '@/utils/config'
import { ElMessage } from 'element-plus'

const baseConfig = {
  baseURL: baseUrl,
  withCredentials: true,
  responseType: 'json',
  timeout: 3000,
  headers: {
    'Content-Type': 'application/json'
  }
}

function showError(msg) {
  ElMessage.error({
    dangerouslyUseHTMLString: true,
    message: msg ? msg.replace(/\n/g, '<br>') : defaultError
  })
}

// 静默，没有有全屏loading，数据为json格式
const instanceQuiet = axios.create(
  Object.assign({}, baseConfig, {
    transformRequest: [
      function (data) {
        return JSON.stringify(data)
      }
    ],
    transformResponse: [
      function (data) {
        try {
          // 数据处理应放在拦截器中，一旦此处报错拦截器无法拿到状态码做出相应的错误提示，后期优化
          data = typeof data === 'string' ? JSON.parse(data) : data
          // 如果返回的结果没有errno，将被直接返回
          if (data.errno && data.errno !== 0) {
            showError(data.errmsg)
            return Promise.reject(data)
          }
          return data
        } catch (error) {
          console.warn('error:', error)
        }
      }
    ]
  })
)

instanceQuiet.interceptors.request.use(
  (config) => {
    if (config.url.includes('mock-api') || config.url.includes('http')) {
      config.baseURL = '/'
    }
    return config
  },
  (error) => {
    showError(defaultError)
    return Promise.reject(error)
  }
)
instanceQuiet.interceptors.response.use(
  function (response) {
    const res = response.data
    return res
  },
  function (error) {
    showError(defaultError)
    return Promise.reject(error)
  }
)

export default instanceQuiet
